package com.tingyuge.base.thread.tools;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by xiaodao
 * date: 2020/3/23
 */
public class Cyclic {

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        //barrier action 等到最后一个线程
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
            System.out.println("hello world ");
        });
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                new Thread(()->{
                    try {
                        Thread.sleep((long)(Math.random() * 2000));
                        int randomInt = new Random().nextInt(500);
                        System.out.println("hello "+ randomInt);
                        cyclicBarrier.await();
                        System.out.println("word "+ randomInt);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }

        }
    }
}
